
var i = Math.random()*500;
var j = Math.random()*500;
var i2 = Math.random()*500;
var j2 = Math.random()*500;

var coinImage = new Image();
coinImage.src = "images/coin-sprite-animation.png";

function gameLoop () {
  window.requestAnimationFrame(gameLoop);
    coin.update();
  coin.render();
}
// Start the game loop as soon as the sprite sheet is loaded
coinImage.addEventListener("load", gameLoop);


function sprite (options) {		
			
   var that = {},
        frameIndex = 0,
        tickCount = 0,
        ticksPerFrame = options.ticksPerFrame || 0;
        numberOfFrames = options.numberOfFrames || 1;
        
	
    that.context = options.context;
    that.width = options.width;
    that.height = options.height;
    that.image = options.image;
    
    that.loop = options.loop;

        that.update = function () {
        tickCount += 1;			
        if (tickCount > ticksPerFrame) {
        	tickCount = 0;
       	// If the current frame index is in range
            if (frameIndex < numberOfFrames - 1) {	

            // Go to the next frame
            frameIndex += 1; 
             } else if (that.loop) {
                frameIndex = 0;
                
       } 
       else {
       frameIndex = !0;
       
       }}
    };

    
    
    
    	that.render = function () { 
    		
    		// Clear the canvas
    that.context.clearRect(i, j, that.width, that.height);

that.context.clearRect(i2, j2, that.width, that.height);


  // Draw the animation     
    that.context.drawImage( 
    	that.image,          
		frameIndex * that.width / numberOfFrames,
           0,
           that.width / numberOfFrames, 
           that.height,
           i, 
           j,
           that.width / numberOfFrames,
 			that.height);
 			
 			
 		



    // Draw the animation     
    that.context.drawImage( 
    	that.image,          
		frameIndex * that.width / numberOfFrames,
           0,
           that.width / numberOfFrames, 
           that.height,
           i2, 
           j2,
           that.width / numberOfFrames,
 			that.height);
 			
 			
 			
 			
 			
 };
    
    
    return that;
}

var canvas = document.getElementById("coinAnimation");
canvas.width = 1000;
canvas.height = 1000;


var coin = sprite({
    context: canvas.getContext("2d"),
    width: 1000,
    height: 1000,
    image: coinImage,
    numberOfFrames: 10,
    ticksPerFrame: 4
});
